package jianzhioffer;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

// 剑指 Offer 58 - I. 翻转单词顺序
public class ReverseWords {

    public static void main(String[] args) {

        System.out.println(reverseWords2("a good   example"));
    }

    // API
    public static String reverseWords(String s) {
        String[] s1 = s.split(" ");
        List<String> collect = Arrays.stream(s1).filter(item -> !"".equals(item)).collect(Collectors.toList());
        Collections.reverse(collect);
        String[] strings = collect.toArray(new String[0]);
        return String.join(" ", strings).trim();
    }

    // 双指针
    public static String reverseWords2(String s) {
        s = s.trim();
        int i = s.length() - 1;
        int j = s.length() - 1;
        StringBuffer stringBuffer = new StringBuffer();
        while (i >= 0) {
            while (i >= 0 && s.charAt(i) != ' ') {
                i--;
            }
            stringBuffer.append(s.substring(i + 1, j + 1) + " ");
            while (i >= 0 && s.charAt(i) == ' ') {
                i--;
            }
            j = i;
        }
        return stringBuffer.toString().trim();
    }
}
